package com.cskaoyan.order.mq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @auther cskaoyan
 * @date 2022/7/12:17:23
 */
@Component
@Slf4j
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        // 创建Producer
        producer = new DefaultMQProducer("delay_order_cancel_producer");

        // 设置nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876");

        try {
            // 启动produer
            producer.start();
        } catch (MQClientException e) {
            log.error("启动producer失败" + e);
        }

    }


    public boolean sendDelayOrderCancelMessage(String orderId) {
        // 一定要输出日志
        log.info("需要发送的订单编号:" + orderId);
        // 准备好待发送的延迟消息
        Message message = null;
        message = new Message("delay_order_cancel", orderId.getBytes(Charset.forName("utf-8")));
        // 设置消息的延迟级别
        // 3 10s
        message.setDelayTimeLevel(16);

        // 发送消息
        SendResult sendResult = null;
        Exception ex = null;
        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
            ex = e;
        } catch (RemotingException e) {
            e.printStackTrace();
            ex = e;
        } catch (MQBrokerException e) {
            e.printStackTrace();
            ex = e;
        } catch (InterruptedException e) {
            e.printStackTrace();
            ex = e;
        }

        if (ex != null) {
            log.error("发送时出现异常，发送失败" + ex);
            return false;
        }

        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            // 消息发送成功
            log.info("消息发送成功，订单编号:"+orderId);
            return true;
        }

        // 消息发送失败
        return false;
    }
}
